package com.miluGame.util;


import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Util {
	public static final String DATE_PATTEN_yyyy_MM_dd = "yyyy-MM-dd";
	public static final String DATE_PATTEN_yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
	private static Log log = LogFactory.getLog(Util.class);
	
	private Util(){}
	
	/**
	 * 控制台打印方法
	 * */
	public static void print(String str){
		System.out.println(str);
	}
	
	public static void print(Exception e){
		e.printStackTrace();
	}
	
	/**
	 * 输出
	 * */
	public static void out(HttpServletResponse response, String str){
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			out.close();
		}
	}
	
	/**
	 * 弹窗
	 * */
	public static void alert(HttpServletResponse response, String str){
		PrintWriter out = null;
		try {
			out = response.getWriter();
			StringBuffer sb = new StringBuffer();
			sb.append("<script type='text/javascript'>")
				.append("alert('")
				.append(str)
				.append("');");
			sb.append("</script>");
			out.print(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			out.close();
		}
	}
	
	/**
	 * 获取登录着IP
	 * */
	public static String getIp(HttpServletRequest request){
        if (request == null){
            return null;
        }
        String ipaddress = "";
        if (request.getHeader("x-forwarded-for") == null){
            ipaddress = request.getRemoteAddr();
        }
        else{
            ipaddress = request.getHeader("x-forwarded-for");
        }
        if(ipaddress != null){
            String[] s = ipaddress.split(",");
            if(s.length==1)
            {
                ipaddress = s[0].trim();
            }
            else if(s.length > 1)
            {
                ipaddress = s[s.length - 2].trim();
            }
        }
        return ipaddress;
    }

	
	/**
	 * 跳转
	 * */
	public static void jump(HttpServletResponse response, String url){
		PrintWriter out = null;
		try {
			out = response.getWriter();
			StringBuffer sb = new StringBuffer();
			sb.append("<script type='text/javascript'>")
				.append("window.location.href='")
				.append(url)
				.append("';");
			sb.append("</script>");
			out.print(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			out.close();
		}
	}
	
	
	/**
	 * 计算最大页（页码从0开始）
	 * @param pageNum 每页条数
	 * @param pageCount 总记录条数
	 * @return 最大页
	 * */
	public static int getPageSum(int pageNum, int pageCount){
		if(pageCount < pageNum){
			return 0;
		}else{
			return pageCount%pageNum==0? pageCount/pageNum-1 : pageCount/pageNum;// 最大页
		}
	}
	
	
	
	/**
	 * URL编码
	 * */
	public static String encode(String str,String encoding){
		try {
			return URLEncoder.encode(str,encoding);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * URL解码
	 * */
	public static String unEncode(String str,String encoding){
		try {
			return URLDecoder.decode(str,encoding);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 日期格式化
	 * */
	public static String formatDate(Date date, String patten){
		if(date == null){
			return "";
		}
		SimpleDateFormat sdf=new SimpleDateFormat(patten);
		return sdf.format(date);
	}
	
	/**
	 * 字符串转日期
	 * */
	public static Date strToDate(String strDate, String patten){
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat(patten);
		try {
			Date date = simpleDateFormat.parse(strDate);
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 日期加减指定的天数
	 * @param date 要进行计算的日期
	 * @param day 正数+指定天数、负数-指定天数
	 * @return Date
	 * */
	public static Date dateAdd(Date date, int day){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, day);
		return calendar.getTime();
	}
	
	/**
	 * 获取指定时间段的所有日期（开始日期必须小于结束日期）
	 * @param start 开始日期
	 * @param end 结束日期
	 * @return List<Date> 返回日期中不包括开始日期，不包括结束日期
	 * */
	public static List<Date> getIntervalDate(Date start,Date end){
		List<Date> list = new ArrayList<Date>();
		Calendar startCal = Calendar.getInstance();
		Calendar endCal = Calendar.getInstance();
		startCal.setTime(start);
		endCal.setTime(end);
		long lFlag = (end.getTime() - start.getTime())/1000/60/60/24;
		for(int i=0;i<lFlag-1;i++){
			startCal.add(Calendar.DATE, 1);
			list.add(startCal.getTime());
		}
		return list;
	}
	
	/**
	 * 获取一段时间的每一天
	 * @param start
	 * @param end
	 * @return	每一天的时间集合对象
	 */
	public static List<String> getStringIntervalDate(Date start,Date end){
		List<String> list = new ArrayList<String>();
		Calendar startCal = Calendar.getInstance();
		Calendar endCal = Calendar.getInstance();
		startCal.setTime(start);
		endCal.setTime(end);
		list.add(formatDate(startCal.getTime(), "yyyy-MM-dd"));
		long lFlag = (end.getTime() - start.getTime())/1000/60/60/24;
		for(int i=0;i<lFlag-1;i++){
			startCal.add(Calendar.DATE, 1);
			list.add(formatDate(startCal.getTime(), "yyyy-MM-dd"));
		}
		list.add(formatDate(endCal.getTime(), "yyyy-MM-dd"));
		return list;
	}
	
	/**
	 * 重新倒序封装成List集合对象
	 * @param list
	 * @return
	 */
	public static List<String> orderDescDate(List<String> list){
		List<String> dateOrderList = new ArrayList<String>();
		for(int i= list.size()-1;i>=0;i--){
			dateOrderList.add(list.get(i));
		}
		return dateOrderList;
	}
	/**
	 * 获取指定日期的时间段(从零点开始)
	 * 比如日期为2013-09-02，当前时间为12点，那么返回的开始日期为2013-09-02 00:00:00和2013-09-02 12:00:00
	 * @param targetDate 目标日期(Date对象)
	 * @return Map,包括2个值，key分别为beginDate和endDate
	 */
	public static Map<String, String> getTargetTime(Date targetDate) {
		
		Calendar cl = Calendar.getInstance();
		cl.setTime(targetDate);
		
		int month = cl.get(Calendar.MONTH) + 1;
		String monthStr = month > 9 ? String.valueOf(month) : "0" + month;
		
		int day = cl.get(Calendar.DATE);
		String dayStr = day > 9 ? String.valueOf(day) : "0" + day;
		
		int hour = cl.get(Calendar.HOUR_OF_DAY);
		String hourStr = "";
		if (hour > 0) {
			hourStr = (hour > 9 ? String.valueOf(hour) : "0" + hour) + ":00:00";
		} else {
			hourStr = "23:59:59";
		}
		
		StringBuffer dateStr = new StringBuffer();
		dateStr.append(cl.get(Calendar.YEAR)).append("-").append(monthStr).append("-").append(dayStr);
		
		StringBuffer begin = new StringBuffer();
		begin.append(dateStr).append(" 00:00:00");
		
		StringBuffer end = new StringBuffer();
		end.append(dateStr).append(" ").append(hourStr);
		
		Map<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("beginDate", begin.toString());
		resultMap.put("endDate", end.toString());
		
		return resultMap;
	}
	
	/**
	 * 计算百分比
	 * @param obj 要计算的对象
	 * @param 表留小数点位数，如：0.00%传入2
	 * */
	public static String getPercentage(Object obj, int length){
		NumberFormat nf  =  NumberFormat.getPercentInstance();
		nf.setMinimumFractionDigits(length);
		return nf.format(obj);
	}
	
	
}
